package com.cy.lib.widget;

import android.content.Context;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.util.AttributeSet;
import android.view.Gravity;
import android.widget.RadioButton;
import android.widget.RadioGroup;


/**
 * @author CY
 * @date 2014-10-23
 */
public class PagerIndicator extends RadioGroup {

    OnPageChangeListener mOnPageChangeListener;

    public PagerIndicator(Context context) {
        super(context);
    }

    public PagerIndicator(Context context, AttributeSet attrs) {
        super(context, attrs);
        setOrientation(HORIZONTAL);
        setGravity(Gravity.CENTER);
    }

    public void setViewPager(int count, ViewPager viewPager, int resid, OnPageChangeListener listener) {
        if (count == 0) {
            return;
        }
        mOnPageChangeListener = listener;
        removeAllViews();
        int px = dip2px(getContext(), 4);
        int wh = dip2px(getContext(), 12);
        LayoutParams params = new LayoutParams(wh, wh);
        params.setMargins(px, 0, px, 0);
        for (int i = 0; i < count; i++) {
            RadioButton rButton = new RadioButton(getContext());
            if (resid != 0) {
                rButton.setButtonDrawable(resid);
                rButton.setBackgroundResource(0);
            }
            addView(rButton, params);
            if (i == 0) {
                rButton.setChecked(true);
            }
        }
        viewPager.setOnPageChangeListener(onPageChangeListener);
    }

    OnPageChangeListener onPageChangeListener = new OnPageChangeListener() {

        @Override
        public void onPageSelected(int position) {
            // if (position >= getChildCount()) {
            // return;
            // }
            int index = position % getChildCount();
            RadioButton rb = (RadioButton) getChildAt(index);
            rb.setChecked(true);
            if (mOnPageChangeListener != null) {
                mOnPageChangeListener.onPageSelected(index);
            }
        }

        @Override
        public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
            if (mOnPageChangeListener != null) {
                mOnPageChangeListener.onPageScrolled(position, positionOffset, positionOffsetPixels);
            }
        }

        @Override
        public void onPageScrollStateChanged(int state) {
            if (mOnPageChangeListener != null) {
                mOnPageChangeListener.onPageScrollStateChanged(state);
            }
        }
    };

    private int dip2px(Context context, int dip) {
        float density = context.getResources().getDisplayMetrics().density;
        return (int) (density * dip + 0.5f);
    }
}
